'use strict'

const crypto = require('crypto');

module.exports = function(table,sequelize){
	var aesutil = {};

    /**
     * aes加密
     * @param data 待加密内容
     * @param key 必须为32位私钥
     * @returns {string}
     */
    aesutil.encryption = function (data, key, iv) {
        if (!data||data == 'null') {
            return "";
        }
        var algorithm = 'aes-128-cbc';
        var clearEncoding = 'utf8';
        var cipherEncoding = 'base64';
        var cipher = crypto.createCipheriv(algorithm, key,iv);

        var cipherChunks = [];
        cipherChunks.push(cipher.update(data, clearEncoding, cipherEncoding));
        cipherChunks.push(cipher.final(cipherEncoding));
        return cipherChunks.join('');
    }

    /**
     * aes解密
     * @param data 待解密内容
     * @param key 必须为32位私钥
     * @returns {string}
     */
    aesutil.decryption = function (data, key, iv) {
        if (!data||data == 'null') {
            return "";
        }
        console.log('Original cleartext: ' + data);
        var algorithm = 'aes-128-cbc';
        var clearEncoding = 'utf8';
        var cipherEncoding = 'base64';

        var cipherChunks = data;

        var decipher = crypto.createDecipheriv(algorithm, key,iv);
        var plainChunks = [];
        plainChunks.push(decipher.update(cipherChunks, cipherEncoding, clearEncoding));
        plainChunks.push(decipher.final(clearEncoding));
        return plainChunks.join('');
    }

/*    //加密
    function encodeMixnick(str){
        console.log('** encode **');
        console.log(str);
        var key = '751f620ea5c8f930';
        var iv = '2624750004598718';
        str = aesutil.encryption(str,key,iv);
        console.log(str);
        console.log('*****');
        return str;
    }

    //解密
    function decodeMixnick(str){
        console.log('** decode **');
        console.log(str);
        var key = '751f620ea5c8f930';
        var iv = '2624750004598718';
        try{
            str = aesutil.decryption(str,key,iv);
        }catch(e){
            return '';
        }
        console.log(str);
        console.log('*****');
        return str;
    }*/

/*	var iteam = {
		'add':function(){//开团
			return  new Promise((resolve,reject)=>{
				table.groupon_fotile_iteam.create({

				}).then(data=>{
					resolve(data.dataValues);					
				}).catch(err=>{
					console.log('err:',err);
					resolve(false);
				});
			});
		},
		'attend':function(options){//参团
			var options = options||{};
			return  new Promise((resolve,reject)=>{
				table.lux_user.create({
					wangwang_id : options.wangwang,
					realname : options.name,
					telephone : options.phone,
					iteam_id : options.iteamid,
					wechat_id : options.openid||'',
					taobao_id : options.mixnick||'',
					avatar : options.avatar||'',
					service : options.service||''
				}).then(data=>{
					resolve(data.dataValues);					
				}).catch(err=>{
					console.log('err:',err);
					resolve(false);
				});
			});
		},
		'getList':function(iteamid){//获取团队成员
			return new Promise((resolve,reject)=>{
				table.lux_user.findAll({
					attributes:['avatar','realname','service'],
					where:{
						'iteam_id':iteamid
					},
					order:[
						['createdAt','DESC']
					]
				}).then(function(data){
	                if(data!=null){
	                    return resolve(data);                    
	                }else{
	                    return resolve(null);
	                }
	            }).catch((err)=>{
	                console.log('err:',err);
	                return resolve(false);
	            });   
			});
		},
		'count':function(iteamid){//获取团队成员
			return new Promise((resolve,reject)=>{
				table.lux_user.count({
					where:{
						'iteam_id':iteamid
					},
					order:[
						['createdAt','DESC']
					]
				}).then(function(data){
	                if(data!=null){
	                    return resolve(data);                    
	                }else{
	                    return resolve(null);
	                }
	            }).catch((err)=>{
	                console.log('err:',err);
	                return resolve(false);
	            });   
			});
		}
	}*/

    var user = {
        'insert':function(userchannelid,type){//插入新数据
        	var obj = {
                    'award':'{"1":0,"2":0,"3":0,"4":0}',
                    'chance':3,
                    'share':3,
                    'lotterychance':1
                };
            type==1 ? obj['mixnick']=userchannelid : obj['openid']=userchannelid;
            return new Promise((resolve,reject)=>{
                table.lux_user.create(obj).then(function(data){
                    return resolve(data.dataValues);
                }).catch((err)=>{
                    console.log('err:',err);
                    return resolve(false);
                });
            });
        },
        'selectOneById':function(id){//查询用户数据
            return new Promise((resolve,reject)=>{
                table.lux_user.findOne({
                    where:{
                        'user_id' : id
                    }
                }).then(function(data){
                    if(data!=null){
                        return resolve(data.dataValues);
                    }else{
                        return resolve(null);
                    }
                }).catch((err)=>{
                    console.log('err:',err);
                    return resolve(false);
                });
            });
        },
        'selectOneByMixnick':function(mixnick){//查询用户数据
            return new Promise((resolve,reject)=>{
                table.lux_user.findOne({
                    where:{
                        'mixnick' : mixnick
                    }
                }).then(function(data){
                    if(data!=null){
                    	console.log('***1');
                        return resolve(data.dataValues);
                    }else{
                    	console.log('***2');
                        return resolve(null);
                    }
                }).catch((err)=>{
                    console.log('err:',err);
                    return resolve(false);
                });
            });
        },
        'selectOneByOpenid':function(openid){//查询用户数据
            return new Promise((resolve,reject)=>{
                table.lux_user.findOne({
                    where:{
                        'openid' : openid
                    }
                }).then(function(data){
                    if(data!=null){
                        return resolve(data.dataValues);
                    }else{
                        return resolve(null);
                    }
                }).catch((err)=>{
                    console.log('err:',err);
                    return resolve(false);
                });
            });
        },
        'updateOneById':function(id,attr){
            return new Promise((resolve,reject)=>{
                table.lux_user.update(attr,{
                    where:{
                        'user_id' : id
                    }
                }).then(function(data){
                    return resolve(data[0]);
                }).catch((err)=>{
                    console.log('err:',err);
                    return resolve(false);
                });
            });
        },
        'count':function(attrObj){
            return new Promise((resolve,reject)=>{
                table.lux_user.count({
                    where:attrObj
                }).then(function(data){
                    if(data!=null){
                        return resolve(data);                    
                    }else{
                        return resolve(null);
                    }
                }).catch((err)=>{
                    console.log('err:',err);
                    return resolve(false);
                });
            });
        },
        'getAvatar':function (mixNick,client) {//获取头像
            return new Promise(function(resolve) {
            var mixNickDecode = decodeURIComponent(mixNick);
            console.log(mixNickDecode);
            client.execute('taobao.user.avatar.get', {
                    'nick':mixNickDecode
                }, function(error, response) {
                    console.log(error,response);
                    if (!error) 
                    {
                          if(response.avatar)
                          {
                            resolve(response.avatar);   
                          }
                          else
                          {
                            resolve('https://assets.alicdn.com/app/sns/img/default/avatar-120.png');   
                          }                     

                    }
                    else {
                      resolve('https://assets.alicdn.com/app/sns/img/default/avatar-120.png');

                    } 

                });  
            });
        }
    }

	var wrapper = function(data,code){
		var reobj = {
			errCode:0,
			msg:'ok',
			data:{}
		}
		if(!data){
			reobj.errCode = code;
		}else{
			reobj.data = data;
		}
		return JSON.stringify(reobj);
	}
	return {
		wrapper: wrapper,
		user: user,
		aesutil:aesutil
	}
}